from django.http import HttpResponse,Http404,HttpResponseRedirect
from django.shortcuts import render
import datetime

from mysite.forms import ContactForm
from django.core.mail import send_mail

def hello(request):
    return HttpResponse("hello world")

def current_datetime(request):
    now = datetime.datetime.now()
    html = "It is now {{ now }}"
    return render(request,html,{"now":now})

def hours_ahead(request,offset):
    try:
        offset = int(offset)
    except Exception as e:
        raise Http404()
    now = datetime.datetime.now()
    dt = now+datetime.timedelta(hours=offset)
    html = "after %s hours,It will be %s" % (offset,dt)
    return HttpResponse(html)


def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email','noreply@example.com'),
                ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(
            initial={'subject':'I love your site'}
        )

    return render(request,'contact_form.html',{'form':form})
